package com.rongshu.view.home.fragment.dialog;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialogFragment;
import android.support.v4.app.DialogFragment;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;

import com.rongshu.base.BuildConfig;
import com.rongshu.R;
import com.rongshu.utils.Constant;
import com.rongshu.utils.RandomCommentUtil;
import com.rongshu.view.discovery.bean.AuthorDetailBean;
import com.rongshu.view.home.activity.SearchAtUserActivity;
import com.utils.FastClickUtils;
import com.widget.titlebar.ImmersionBar;
import com.widget.titlebar.OnKeyboardListener;
import com.widget.toast.ToastUtils;

import java.util.LinkedHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;
import static com.rongshu.view.home.fragment.dialog.ArticleCommentDialog.REQUEST_AT_USER;

/**
 * created by zhengweis on 2019/7/10.
 * description：
 */
public class InputNoteDialog extends BottomSheetDialogFragment {
    @BindView(R.id.edt_chat_input)
    EditText edtChatInput;
    //dialog
    private Dialog dialog;
    //正则
    private String REGEX = "@[\\u4e00-\\u9fa5\\w….-]+ ";
    //评论
    //@的用戶信息
    private LinkedHashMap<String, AuthorDetailBean> authorDetailBeanMap = new LinkedHashMap<>();
    private Pattern pattern = null;
    private Matcher matcher = null;
    //listener
    private OnDialogInputListener listener = null;
    //避免@时候键盘关闭
    private boolean isBackFromAT = false;

    public static InputNoteDialog getInstance(String content, String replyContent, LinkedHashMap<String, AuthorDetailBean> map) {
        InputNoteDialog dialog = new InputNoteDialog();
        Bundle bundle = new Bundle();
        bundle.putString(Constant.INTENT_DATA, content);
        bundle.putString(Constant.INTENT_MESSAGE, replyContent);
        bundle.putSerializable(Constant.INTENT_LIST, map);
        dialog.setArguments(bundle);
        return dialog;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //给dialog设置主题为透明背景 不然会有默认的白色背景
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.input_dialog);
    }

    @Override
    public View onCreateView(@Nullable LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 在这里将view的高度设置为精确高度，即可屏蔽向上滑动不占全屏的手势。
        //如果不设置高度的话 会默认向上滑动时dialog覆盖全屏
        View view = inflater.inflate(R.layout.comment_input_view, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        if (getArguments() != null) {
            Bundle bundle = getArguments();
            String content = bundle.getString(Constant.INTENT_DATA);
            String replyContent = bundle.getString(Constant.INTENT_MESSAGE);
            authorDetailBeanMap = (LinkedHashMap<String, AuthorDetailBean>) bundle.getSerializable(Constant.INTENT_LIST);
            //创建富文本
            SpannableStringBuilder builder = new SpannableStringBuilder();
            builder.append(content);
            //正则
            Pattern pattern = Pattern.compile(REGEX);
            Matcher matcher = pattern.matcher(content);
            while (matcher.find()) {
                builder.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color_3cc051)),
                        matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            edtChatInput.setHint(TextUtils.isEmpty(replyContent) ? getString(R.string.input_comment_dialog_hint) : replyContent);
            edtChatInput.setText(builder);
            edtChatInput.setSelection(builder.length());
        }
        //输入框数据监听
        edtChatInput.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN) {
                    LinkedHashMap<Integer, Integer> atEndList = new LinkedHashMap<>();
                    String content = edtChatInput.getText().toString();
                    //正则
                    pattern = Pattern.compile(REGEX);
                    matcher = pattern.matcher(content);
                    while (matcher.find()) {
                        atEndList.put(matcher.start(), matcher.end());
                    }

                    //获取输入框光标位置
                    int position = edtChatInput.getSelectionStart();
                    for (LinkedHashMap.Entry<Integer, Integer> entry : atEndList.entrySet()) {
                        if ((position < entry.getValue() && position > entry.getKey()) || position == entry.getValue()) {
                            //获取该位置的数据
                            String key = content.substring(entry.getKey(), entry.getValue());
                            content = content.replace(key, "");
                            //创建富文本
                            SpannableStringBuilder builder = new SpannableStringBuilder();
                            builder.append(content);
                            if (!TextUtils.isEmpty(content)) {
                                //正则
                                matcher = pattern.matcher(content);
                                while (matcher.find()) {
                                    builder.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color_3cc051)),
                                            matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                }
                            }
                            edtChatInput.setText(builder);
                            edtChatInput.setSelection(builder.length());

                            if (authorDetailBeanMap.containsKey(key)) {
                                authorDetailBeanMap.remove(key);
                            }
                            return true;
                        }
                    }
                    return false;
                }
                return false;
            }
        });
    }

    /**
     * 如果想要点击外部消失的话 重写此方法
     */
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        dialog = super.onCreateDialog(savedInstanceState);
        //设置点击外部可消失
        dialog.setCanceledOnTouchOutside(true);
        Window win = dialog.getWindow();
        //这里设置dialog的进出动画
        win.setWindowAnimations(R.style.input_anim);
        ImmersionBar.with(this, dialog).keyboardEnable(true,
                WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN |
                        WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
                .setOnKeyboardListener(new OnKeyboardListener() {
                    @Override
                    public void onKeyboardChange(boolean isPopup, int keyboardHeight) {
                        if (!isPopup && !isBackFromAT) {
                            dismiss();
                        }
                        isBackFromAT = false;
                    }
                }).init();
        return dialog;
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        if (listener != null) {
            listener.dimiss(authorDetailBeanMap, edtChatInput.getText().toString(), edtChatInput.getHint().toString());
        }
        ImmersionBar.with(this).destroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_AT_USER) {
                if (dialog != null) {
                    ImmersionBar.with(this, dialog).keyboardEnable(true,
                            WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN |
                                    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
                            .init();
                }
                isBackFromAT = true;
                AuthorDetailBean authorDetailBean = (AuthorDetailBean) data.getSerializableExtra(Constant.INTENT_DATA);
                String content = null;
                //获取输入框内容
                String inputString = edtChatInput.getText().toString();
                if (authorDetailBean != null) {
                    //返回内容
                    String bi_name = "@" + authorDetailBean.getBi_name() + " ";
                    if (authorDetailBeanMap.containsKey(bi_name)) {//@同一个人2次不进行处理
                        return;
                    }
                    //@集合
                    authorDetailBeanMap.put(bi_name, authorDetailBean);
                    content = TextUtils.isEmpty(inputString) ? bi_name : inputString + bi_name;
                    //创建富文本
                    SpannableStringBuilder builder = new SpannableStringBuilder();
                    builder.append(content);
                    //正则
                    Pattern pattern = Pattern.compile(REGEX);
                    Matcher matcher = pattern.matcher(content);
                    while (matcher.find()) {
                        builder.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color_3cc051)),
                                matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    }
                    edtChatInput.setText(builder);
                    edtChatInput.setSelection(content.length());
                } else {
                    if (!TextUtils.isEmpty(inputString)) {
                        edtChatInput.setSelection(inputString.length());
                    }
                }
            }
        }
    }

    @OnClick({R.id.iv_at, R.id.txt_send})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_at:
//                if (BuildConfig.DEBUG) {
//                    String commentMsg = RandomCommentUtil.getInstance().getCommentMsg();
//                    edtChatInput.setText(commentMsg);
//                } else if (!FastClickUtils.isFastClick()) {
                    Intent intent = new Intent(getActivity(), SearchAtUserActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivityForResult(intent, REQUEST_AT_USER);
//                }
                break;
            case R.id.txt_send:
                if (FastClickUtils.isFastClick()) {
                    return;
                }
                String content = edtChatInput.getText().toString();
                if (TextUtils.isEmpty(content)) {
                    ToastUtils.show("输入信息不能为空");
                    return;
                }
                if (listener != null) {
                    listener.sendCommentSuccess(authorDetailBeanMap, content);
                }
                break;
        }
    }

    /**
     * 一定要销毁dialog，设置为null，防止内存泄漏
     */
    public void dismissDialog() {
        edtChatInput.setHint("");
        edtChatInput.setText("");
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
            dialog = null;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        dismissDialog();
    }

    public interface OnDialogInputListener {
        //评论、回复成功
        void sendCommentSuccess(LinkedHashMap<String, AuthorDetailBean> map, String content);

        void dimiss(LinkedHashMap<String, AuthorDetailBean> map, String content, String replyContent);
    }

    public void setOnDialogInputListener(OnDialogInputListener dimissListener) {
        this.listener = dimissListener;
    }
}
